package com.linkin.homepage.view.refresh;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewParent;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.linkin.homepage.R;
import com.linkin.homepage.base.net.IResponseData;
import com.linkin.homepage.base.recycleview.RecyclerViewUtils;
import com.linkin.homepage.base.util.NetStatusUtils;
import com.linkin.homepage.bean.BaseListBean;
import com.linkin.homepage.util.ToastUitl;
import com.linkin.homepage.view.refresh.smallrefreshlayout.RefreshState;
import com.linkin.homepage.view.refresh.smallrefreshlayout.SmallRefreshLayout;

import java.util.List;

public class RefreshViewUtils {

    public interface OnLoadMoreListener {
        void onLoadMore();
    }

    public static void setOnRefreshListener(View view, SmallRefreshLayout.OnRefreshListener listener) {
        SmallRefreshLayout refreshLayout = getRefreshLayout(view);
        if (refreshLayout != null) {
            refreshLayout.setOnRefreshListener(listener);
            if (listener != null) {
                refreshLayout.setRefreshEnabled(true);
            }
        }
    }

    public static View setOnLoadMoreListener(
            RecyclerView recyclerView, final OnLoadMoreListener listener) {
        return setOnLoadMoreListener(recyclerView, listener, R.layout.refresh_footer, 10);
    }

    public static View setOnLoadMoreListener(
            RecyclerView recyclerView, final OnLoadMoreListener listener, int loadMoreLayoutId, int preloadCount) {
        if (recyclerView == null || listener == null) {
            return null;
        }

        View footerView = LayoutInflater.from(recyclerView.getContext())
                .inflate(loadMoreLayoutId, recyclerView, false);
        RecyclerViewUtils.setFooterView(recyclerView, footerView);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private boolean mAlreadyLoadMore = true;

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (dy > 0 && canLoadMore(recyclerView, mAlreadyLoadMore, preloadCount)) {
                    mAlreadyLoadMore = true;
                    setFooterState(recyclerView, RefreshFooterState.LOADING);
                    listener.onLoadMore();
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                mAlreadyLoadMore = false;
            }
        });

        RefreshFooterView refreshFooterView = getFooterView(recyclerView);
        if (refreshFooterView != null) {
            refreshFooterView.setGoneViewClickListener(v -> {
                setFooterState(recyclerView, RefreshFooterState.LOADING);
                listener.onLoadMore();
            });
            refreshFooterView.setErrorViewClickListener(v -> {
                if (NetStatusUtils.isConnected(recyclerView.getContext())) {
                    setFooterState(recyclerView, RefreshFooterState.LOADING);
                    listener.onLoadMore();
                } else {
                    ToastUitl.showShort("网络未连接，请检查网络设置后重试！");
                }
            });
        }
        return footerView;
    }

    public static void setRefreshing(View view) {
        SmallRefreshLayout refreshLayout = getRefreshLayout(view);
        if (refreshLayout != null) {
            refreshLayout.setRefreshing(true);
        }
    }

    public static boolean isRefreshing(View view) {
        return getRefreshState(view) != RefreshState.DEFAULT;
    }

    public static int getRefreshState(View view) {
        SmallRefreshLayout refreshLayout = getRefreshLayout(view);
        if (refreshLayout != null) {
            return refreshLayout.getRefreshState();
        }
        return RefreshState.DEFAULT;
    }

    public static void onRefreshComplete(View view) {
        SmallRefreshLayout refreshLayout = getRefreshLayout(view);
        if (refreshLayout != null) {
            refreshLayout.setRefreshing(false);
        }
    }

    public static void onLoadMoreComplete(final RecyclerView recyclerView, int footerState) {
        View footerView = getFooterView(recyclerView);
        if (footerView != null
                && footerView.getWindowToken() != null
                && recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_SETTLING
                && (footerState == RefreshFooterState.GONE || footerState == RefreshFooterState.END)) {
            recyclerView.stopScroll();
        }
        if (setFooterState(recyclerView, footerState)
                && footerView != null
                && footerView.getWindowToken() != null) {
            recyclerView.requestLayout();
        }
    }

    public static void onLoadMoreComplete(final RecyclerView recyclerView, IResponseData r) {
        if (r.checkErrorCode()) {
            setFooterState(recyclerView, RefreshFooterState.END);
        } else {
            setFooterState(recyclerView, RefreshFooterState.ERROR);
        }
    }

    public static void onLoadMoreComplete(final RecyclerView recyclerView, BaseListBean listBean, int pageIndex) {
        onLoadMoreComplete(recyclerView, listBean, pageIndex, 20);
    }

    public static void onLoadMoreComplete(final RecyclerView recyclerView, BaseListBean listBean, int pageIndex, int pageLimit) {
        if (listBean != null) {
            if (listBean.pageCount > 0 && listBean.pageCount <= pageIndex
                    || listBean.pageNum > 0 && listBean.pageNum <= pageIndex
                    || listBean.totalIndex > 0 && listBean.totalIndex <= pageIndex
                    || listBean.inforList == null
                    || listBean.inforList.size() < pageLimit) {
                onLoadMoreComplete(recyclerView, RefreshFooterState.END);
            } else {
                onLoadMoreComplete(recyclerView, RefreshFooterState.GONE);
            }
        }
    }

    public static void onLoadMoreComplete(final RecyclerView recyclerView, List list) {
        onLoadMoreComplete(recyclerView, list, 20);
    }

    public static void onLoadMoreComplete(final RecyclerView recyclerView, List list, int pageLimit) {
        if (list == null || list.size() < pageLimit) {
            onLoadMoreComplete(recyclerView, RefreshFooterState.END);
        } else {
            onLoadMoreComplete(recyclerView, RefreshFooterState.GONE);
        }
    }

    public static int getFooterState(final RecyclerView recyclerView) {
        RefreshFooterView refreshFooterView = getFooterView(recyclerView);
        if (refreshFooterView != null) {
            return refreshFooterView.getFooterState();
        }
        return RefreshFooterState.GONE;
    }

    public static boolean setFooterState(final RecyclerView recyclerView, int footerState) {
        RefreshFooterView refreshFooterView = getFooterView(recyclerView);
        return refreshFooterView != null && refreshFooterView.setFooterState(footerState);
    }

    public static RefreshFooterView getFooterView(RecyclerView recyclerView) {
        View view = RecyclerViewUtils.getFooterView(recyclerView);
        if (view instanceof RefreshFooterView) {
            return (RefreshFooterView) view;
        }
        return null;
    }

    private static SmallRefreshLayout getRefreshLayout(View view) {
        if (view != null) {
            ViewParent viewParent = view.getParent();
            if (viewParent instanceof SmallRefreshLayout) {
                return (SmallRefreshLayout) viewParent;
            }
        }
        return null;
    }

    private static boolean canLoadMore(RecyclerView recyclerView, boolean alreadyLoadMore, int preCount) {
        if (recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING
                && alreadyLoadMore) {
            return false;
        }

        final RefreshFooterView footerView = getFooterView(recyclerView);
        if (footerView == null || !footerView.canLoadMore()) {
            return false;
        }

        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (layoutManager.getChildCount() <= 1) {
            return false;
        }

        View lastChild = recyclerView.getChildAt(recyclerView.getChildCount() - 1);
        int position = recyclerView.getChildLayoutPosition(lastChild);
        if (position < 0) {
            return false;
        }

        int totalItemCount = layoutManager.getItemCount();
        return (position + preCount >= totalItemCount);
    }

    private static void postScrollToEnd(RecyclerView recyclerView) {
        recyclerView.post(() -> {
            int endPos = recyclerView.getAdapter().getItemCount() - 1;
            if (endPos >= 0) {
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                if (layoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
                    linearLayoutManager.scrollToPositionWithOffset(endPos, 0);
                } else {
                    recyclerView.scrollToPosition(endPos);
                }
            }
        });
    }
}
